<template>
  <el-dialog :title="title" :visible.sync="dialogFormVisible">
    <el-form :model="form">
      <el-form-item label="课程名称" :label-width="formLabelWidth">
        <el-input
          v-model="form.courseName"
          autocomplete="off"
          :disabled="true"
        ></el-input>
      </el-form-item>
      <el-form-item label="章节名称" :label-width="formLabelWidth">
        <el-input v-model="form.sectionName" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="章节描述" :label-width="formLabelWidth">
        <el-input v-model="form.description" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="章节排序" :label-width="formLabelWidth">
        <el-input v-model="form.orderNum" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取 消</el-button>
      <el-button type="primary" @click="onSubmit">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { saveOrUpdateSection } from '@/api/course-content'

export default {
  name: 'SectionDialogCreateOrEdit',
  data () {
    return {
      isCreate: false,
      title: '',
      dialogFormVisible: false,
      initData: {},
      form: {
        id: undefined,
        couseId: 0,
        courseName: '',
        sectionName: '',
        description: '',
        orderNum: 0,
        status: 0
      },
      formLabelWidth: '120px'
    }
  },
  created () {
    this.initData = Object.assign({}, this.form)
  },
  methods: {
    onSubmit () {
      saveOrUpdateSection(this.form)
        .then((res) => {
          const info = this.isCreate ? '添加章节' : '更新章节'
          if (res.data.code === '000000') {
            this.$message.success(`${info}成功`)
            this.$emit('change')
          } else {
            this.$message.error(`${info}失败`)
          }
        })
        .finally(() => {
          this.dialogFormVisible = false
        })
    },
    showAndInit (course, section) {
      this.dialogFormVisible = true
      this.form = Object.assign({}, this.initData)
      // 编辑
      if (section) {
        this.isCreate = false
        this.title = '更新章节'
        Object.assign(this.form, section)
      } else {
        this.isCreate = true
        this.title = '添加章节'
      }
      this.form.couseId = course.id
      this.form.courseName = course.courseName
    }
  }
}
</script>
